package com.xxxt.wsc.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xxxt.dao.SummarizeMapper;
import com.xxxt.entity.ClassGrade;
import com.xxxt.entity.Student;
import com.xxxt.entity.Summarize;
import com.xxxt.utils.CreateWord;
import com.xxxt.utils.DateUtil;
import com.xxxt.utils.FileUploadUtil;
import com.xxxt.utils.PracticeTestifyUtil;
import com.xxxt.utils.UUIDUtil;
import com.xxxt.utils.ZipzipUtil;
import com.xxxt.wsc.service.SummarizeService;

/**
 * @description:
 * @author:wsc
 * @date:2020年6月12日 下午3:59:02
 */
@Service
@Transactional
public class SummarizeServiceImpl implements SummarizeService{

	static final String t = "teacher";
	
	@Autowired
	SummarizeMapper summarizeMapper;
	
	@Override
	public boolean addSummarize(String title, String content, String summarizeType, String sno) {
		Student student = new Student();
		student.setSno(sno);
		Summarize summarize = new Summarize(UUIDUtil.getUUID(),content,DateUtil.getDate(),summarizeType,title,student);
		int i = summarizeMapper.addSummarize(summarize);
		if(i>0) {
			return true;
		}
		return false;
	}

	@Override
	public boolean deleteSummarize(String id) {
		int i = summarizeMapper.deleteSummarizeById(id);
		if(i>0) {
			return true;
		}
		return false;
	}

	@Override
	public Summarize querySummarizeById(String id) {
		
		return summarizeMapper.querySummarizeByid(id);
	}

	@Override
	public List<Summarize> querySummarizeByOthers(String classGradeId, String commitTime, String sno, String summarizeType,String tno) {
		Student student = new Student();
		student.setSno(sno);
		ClassGrade classGrade = new ClassGrade();
		classGrade.setClassGradeId(classGradeId);
		student.setClassGrade(classGrade);
		Summarize summarize = new Summarize();
		summarize.setStudent(student);
		summarize.setCommitTime(commitTime);
		summarize.setSummarizeType(summarizeType);
		List<Summarize> list = summarizeMapper.querySummarizeByDynamicSQL(summarize,tno);
		return list;
	}

	@Override
	public boolean updateSummarize(String id, String title, String content, String summarizeType, String sno) {
		Student student = new Student();
		student.setSno(sno);
		Summarize summarize = new Summarize(id,content,null,summarizeType,title,student);
		int i = summarizeMapper.updateSummarizeById(summarize);
		if(i>0) {
			return true;
		}
		return false;
	}

	@Override
	public ResponseEntity<byte[]> downloadOne(HttpServletResponse response,HttpServletRequest request,String summarizeId, String tno) throws Exception {
		//获取总结对象
		Summarize summarize = summarizeMapper.querySummarizeByid(summarizeId);
		//老师目录
		String tdirectory = t+"/"+tno;
		//判断文件夹是否存在
		boolean b = FileUploadUtil.isNotFile(request, tdirectory);
		if(!b) {
			FileUploadUtil.createDirectory(request, response, tdirectory);
		}
		//清空文件夹内容
		PracticeTestifyUtil.deleteAllDirectorysFile(request, tdirectory);
		//将指定的总结生成word
		String summarizeWord = CreateWord.createSummarizeWord(summarize, tdirectory, request, response);
		
		//获取文件
		File file = new File(summarizeWord);
		
		String fileName = file.getName();
	    // 对文件名编码，防止中文文件乱码
	    fileName = FileUploadUtil.getFilename(request, fileName);
//		fileName = new String(fileName.getBytes("utf-8"), "ISO8859-1");
	    // 设置响应头
	    HttpHeaders headers = new HttpHeaders();
	    // 通知浏览器以下载的方式打开文件
	    headers.setContentDispositionFormData("attachment", fileName);
	    // 定义以二进制流的形式下载返回文件数据
	    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	    // 使用SringMVC的ResponseEntity对象封装返回下载数据,Commons FileUpload组件的FileUtils读取文件
	   return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
	                                           headers,HttpStatus.OK);
	}

	@Override
	public ResponseEntity<byte[]> downloadAll(HttpServletResponse response, HttpServletRequest request, String ids,
			String tno) throws UnsupportedEncodingException, FileNotFoundException, IOException {
		//分割总结id
		String[] id = ids.split(",");
		List<Summarize> list = summarizeMapper.querySummarizeByids(id);
		int j = 1;
		for(int i = 0;i<list.size()-1;i++) {
			Summarize s1 = list.get(i);
			Summarize s2 = list.get(i+1);
			if(s1.getStudent().getSno().equals(s2.getStudent().getSno())) {
				s1.getStudent().setName(s1.getStudent().getName()+"_"+j);
				s2.getStudent().setName(s2.getStudent().getName()+"_"+(j+1));
				j++;
			}else {
				j = 1;
			}
		}
		//老师目录
		String tdirectory = t+"/"+tno;
		//判断文件夹是否存在
		boolean b = FileUploadUtil.isNotFile(request, tdirectory);
		if(!b) {
			FileUploadUtil.createDirectory(request, response, tdirectory);
		}
		//清空文件夹内容
		PracticeTestifyUtil.deleteAllDirectorysFile(request, tdirectory);
		//生成word文档
		for(Summarize summarize:list) {
			//将指定的总结生成word
			CreateWord.createSummarizeWord(summarize, tdirectory, request, response);
		}
		//需要压缩的文件
		File file1 = new File(request.getServletContext().getRealPath("/")+"/"+tdirectory);
		//压缩之后的压缩包
		File file2 = new File(
				request.getServletContext().getRealPath("/")+"/"+t+"/"+"临时压缩包目录"+"/"
						+("monthly".equals(list.get(0).getSummarizeType())?"月报":"临时总结")
						+".zip");
		//判断文件夹是否存在
		b = new File(file2.getParent()).exists();
		if(!b) {
			new File(file2.getParent()).mkdir();
		}
		
		//用工具类压缩
		ZipzipUtil.createZip(file1, file2);
		
		//获取文件
		File file = file2;
		//获取文件名
		String fileName = file.getName();
		//解决文件名乱码
		String fileName1 =new String(fileName.getBytes("UTF-8"),"iso-8859-1");
	   
		//读取二进制文件
		byte[] body = null;
	    InputStream is = new FileInputStream(file);
	    body = new byte[is.available()];
	    is.read(body);
	    HttpHeaders headers = new HttpHeaders();
	    
	    //通知浏览器以attachment
	    headers.add("Content-Disposition", "attchement;filename=" + fileName1);
	    
	    //application/octet-stream二进制流数据（最常见的文件下载）。
	    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	   
	    //文件下载的Http协议中的状态最好使用HttpStatus.OK。
	    HttpStatus statusCode = HttpStatus.OK;	    
	    ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);	
		return entity;
	}

}
